//
//  HLSeeMoreViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/6.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLSeeMoreViewController.h"
#import "HttpRequestManager.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "MBProgressHUD+HL.h"
#import "HLUserInfo.h"
#import "HLSeeMoreCell.h"
#import "HLMoreCourse.h"
#import "HLCourseFoldViewController.h"
#import "HLFoldCourse.h"
#import "HLArticleViewController.h"
#import "HLCourseDetailViewController.h"

#define kPageLimit 10

@interface HLSeeMoreViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSUInteger _currenPage;
    NSString *_requesteHeadUrl;
}
@property (nonatomic ,strong) UITableView *tableView;
/** 数据源  */
@property (nonatomic ,strong) NSMutableArray *dataSource;

@end

@implementation HLSeeMoreViewController

#pragma mark - Lazy

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - UI

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
    
    [self configRequestHead];
    
    [self setupRefresh];    
}

- (void)setUI
{
    self.navigationItem.title = self.type == HLSourceTypeVideo ?  @"热门课程":@"推荐视频";
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = HLRGB(245, 245, 245);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = IS_IPHONE_5 ? 120 : 160;
    [_tableView registerClass:[HLSeeMoreCell class] forCellReuseIdentifier:@"HLSeeMoreCell"];
    [self.view addSubview:_tableView];
}

- (void)setupRefresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
    
    [self.tableView.mj_header beginRefreshing];
    [self.tableView.mj_header setAutomaticallyChangeAlpha:YES];
    self.tableView.mj_footer.hidden = YES;
}

- (void)configRequestHead
{
    _requesteHeadUrl = self.type == HLSourceTypeVideo ? kHLRequestGetBookByType : kHLRequestGetCourseByType;
}

#pragma mark - Request

- (void)loadNewUsers
{
    [self cancerRequest];
    
    /**** 数据清空 ****/
    [self.dataSource removeAllObjects];
    
    _currenPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [_requesteHeadUrl signStr];
    params[@"userid"] = [HLUserInfo account].userid;
    params[@"page"] = @(_currenPage);
    params[@"limit"] = @(kPageLimit);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:_requesteHeadUrl parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
         [weakSelf.tableView.mj_header endRefreshing];
        if ([responseObject[@"code"] integerValue] == 200) {
            _currenPage++;
            weakSelf.dataSource = [HLMoreCourse mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.tableView reloadData];
            
            /**** 提示用户数据加载完毕 ****/
            weakSelf.tableView.mj_footer.hidden = NO;
            if (weakSelf.dataSource.count < kPageLimit) {
                _currenPage--;
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                /**** 重置底部状态 ****/
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];

}

- (void)loadMoreUsers
{
    [self cancerRequest];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [_requesteHeadUrl signStr];
    params[@"userid"] = [HLUserInfo account].userid;
    params[@"page"] = @(_currenPage);
    params[@"limit"] = @(kPageLimit);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:_requesteHeadUrl parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        
        [weakSelf.tableView.mj_footer endRefreshing];
        if ([responseObject[@"code"] integerValue] == 200) {
            _currenPage++;
            NSMutableArray *tempArray = [NSMutableArray array];
            tempArray = [HLMoreCourse mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.dataSource addObjectsFromArray:tempArray];
            [weakSelf.tableView reloadData];
            
            /**** 提示用户数据加载完毕 ****/
            if (tempArray.count < kPageLimit) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.tableView.mj_footer endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];

}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLSeeMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HLSeeMoreCell"];
    cell.moreCourse = self.dataSource[indexPath.row];
    cell.categaryTitle.hidden = self.type == HLSourceTypeVideo;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.type == HLSourceTypeVideo){
        HLCourseFoldViewController*detail = [HLCourseFoldViewController new];
        detail.course = self.dataSource[indexPath.row];
        [self.navigationController pushViewController:detail animated:YES];
    }else{
        HLMoreCourse *more = self.dataSource[indexPath.row];
        HLFoldCourse *foldCourse = [HLFoldCourse new];
        if ([more.type integerValue] == 1 ) {
            foldCourse.wkid = more.ID ;
            HLArticleViewController *article = [HLArticleViewController new];
            article.foldCourse = foldCourse;
            [self.navigationController pushViewController:article animated:YES];
        }
        if ([more.type integerValue] == 0) {
            foldCourse.wkid = more.ID;
            HLCourseDetailViewController *couseDetail = [HLCourseDetailViewController new];
            couseDetail.foldCourse = foldCourse;
            [self.navigationController pushViewController:couseDetail animated:YES];
        }
    }
}

#pragma mark - Private

- (void)cancerRequest
{
    /**** 取消之前的请求 ****/
    [[HTTPRequestManager defaultManager].sessionManager.tasks makeObjectsPerformSelector:@selector(cancel)];
}

/***** 界面销毁 取消请求 ****/
- (void)dealloc
{
    [self cancerRequest];
}

@end
